package it.happyisland.framework.web.core;

import it.happyisland.framework.web.AupFilter;
import it.happyisland.framework.web.AupServlet;
import it.happyisland.framework.web.Filter;
import it.happyisland.framework.web.Path;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

public class Router {
	private Map<PathMacher, Method> actions = new HashMap<PathMacher, Method>();
	
	public void load(Class<? extends AupServlet> clazz){
		List<Method> methods = Reflection.methodsWithAnnotation(clazz, Path.class);
		
		for(Method method: methods){
			Path path = method.getAnnotation(Path.class);
			
			PathMacher pathMacher = PathMacher.parse( path.value() );
			actions.put(pathMacher, method);
		}
	}
	
	public void loadForFilter(Class<? extends AupFilter> clazz) {
		List<Method> methods = Reflection.methodsWithAnnotation(clazz, Filter.class);
		
		for(Method method: methods){
			PathMacher pathMacher = PathMacher.parse(PathMacher.FILTER);
			actions.put(pathMacher, method);
		}
	}
	
	public Action resolve(HttpServletRequest req) {
		for(Entry<PathMacher, Method> entry: actions.entrySet()){
			PathMacher matcher = entry.getKey();
			Map<String, String> pathVariables = matcher.match(req.getPathInfo());
			if(pathVariables != null){
				return new Action(entry.getValue(), pathVariables);
			}
		}
		return null;
	}

	
	
}
